/* Copyright (c) 2015 Nordic Semiconductor. All Rights Reserved.
 *
 * The information contained herein is property of Nordic Semiconductor ASA.
 * Terms and conditions of usage are described in detail in NORDIC
 * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT.
 *
 * Licensees are granted free, non-transferable use of the information. NO
 * WARRANTY of ANY KIND is provided. This heading must NOT be removed from
 * the file.
 *
 */

#include "app_util_platform.h"
#include "nrf_gpio.h"
#include "nrf_delay.h"
#include "nrf_log.h"
#include "app_uart.h"
#include "boards.h"
#include "bsp.h"
#include "app_error.h"
#include <string.h>
#include <stdio.h>
#include "at45db.h"

#define UART_TX_BUF_SIZE 256                         /**< UART TX buffer size. */
#define UART_RX_BUF_SIZE 256                           /**< UART RX buffer size. */

static uint8_t spi_tx_buf[PAGE_SIZE];   /**< RX buffer. */
static uint8_t spi_rx_buf[PAGE_SIZE];   /**< RX buffer. */

void uart_error_handle(app_uart_evt_t * p_event) {}
int main(void)
{
    LEDS_CONFIGURE(BSP_LED_0_MASK);
    LEDS_OFF(BSP_LED_0_MASK);

    LEDS_CONFIGURE(1 << SPI_CS_PIN);
    nrf_gpio_pin_set(SPI_CS_PIN);
    uint32_t err_code;
    const app_uart_comm_params_t comm_params =
    {
        RX_PIN_NUMBER,
        TX_PIN_NUMBER,
        RTS_PIN_NUMBER,
        CTS_PIN_NUMBER,
        APP_UART_FLOW_CONTROL_DISABLED,
        false,
        UART_BAUDRATE_BAUDRATE_Baud115200
    };

    APP_UART_FIFO_INIT(&comm_params,
                       UART_RX_BUF_SIZE,
                       UART_TX_BUF_SIZE,
                       uart_error_handle,
                       APP_IRQ_PRIORITY_LOW,
                       err_code);

    APP_ERROR_CHECK(err_code);

    struct flash_ctx *p_flash_ctx = &g_ctx;
    flash_init_ctx(p_flash_ctx, SPI_INSTANCE);
    printf("SPI example\r\n");

    flash_test(p_flash_ctx);

    flash_write_page(p_flash_ctx, 0, spi_tx_buf, sizeof(spi_tx_buf));
    while(flash_check_busy(p_flash_ctx));
    flash_read_page(p_flash_ctx, 0, spi_rx_buf, sizeof(spi_rx_buf));

    for(int i=0; i < 32; i++) {
        printf("%x", spi_rx_buf[i]);
    }

    while(1)
    {
        printf("SPI example\r\n");
        LEDS_INVERT(BSP_LED_0_MASK);
        nrf_delay_ms(1000);
    }
}

